package cn.gaotu.user.service.impl;

import cn.gaotu.basic.constans.BaseConstants;
import cn.gaotu.basic.dto.SmsCodeDto;
import cn.gaotu.basic.excepion.BusinessException;
import cn.gaotu.basic.util.MD5Utils;
import cn.gaotu.basic.util.StrUtils;
import cn.gaotu.user.domain.Logininfo;
import cn.gaotu.user.domain.User;
import cn.gaotu.user.mapper.LogininfoMapper;
import cn.gaotu.user.mapper.UserMapper;
import cn.gaotu.user.service.IUserService;
import cn.gaotu.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void phoneRegister(SmsCodeDto dto) {
        String phone = dto.getPhone();
        String imgCode = dto.getImgCode();
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        //1.校验
        if (imgCode == null ||password == null) {
           throw new BusinessException("参数不能为空");
        }
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("密码不一致,请重新输入");
        }
        //2.短信验证码判断
        String key = BaseConstants.RegisterConstant.REGISTER_SMS_PREFIX + phone;
        Object smsCodeTemp = redisTemplate.opsForValue().get(key);
        if (smsCodeTemp == null) {
            throw new BusinessException("验证码过期,请重新获取");
        }
        if (!imgCode.equalsIgnoreCase(smsCodeTemp.toString().split(":")[0])) {
            throw new BusinessException("验证码不正确,请重新输入");
        }
        //3.保存数据
        User user = dto2User(dto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //同名原则拷贝
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(SmsCodeDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setUsername(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setPassword(md5);
        user.setSalt(salt);
        return user;
    }
}
